package im.ok.back.controller;

import im.ok.back.common.ServerResponse;
import im.ok.back.vo.NewsVo;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("news")
public class NewsController {

    @GetMapping("getNews")
    public ServerResponse getNews() {
        return ServerResponse.createSuccessData(this.getInfo());
    }

    private String readHtml(String urlStr){

        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            inputStream = conn.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            log.error("readHtml error!", e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("inputStream close error!", e);
                }
            }
        }
        return null;
    }

    private List<NewsVo> getInfo() {
        String urlStr = "https://top.baidu.com/board?tab=realtime";
        String html = this.readHtml(urlStr);
        Document doc = Jsoup.parse(html);
        Elements firstLevel = doc.select("div[class=category-wrap_iQLoo horizontal_1eKyQ]");

        int count = 0;
        List<NewsVo> newsList = new ArrayList<>();
        for(Element firstE : firstLevel) {
            // 跳过置顶的新闻，从第一条开始
            if (count == 0) {
                count++;
                continue;
            }
            // 只取10条新闻
            if (count > 10) {
                break;
            }
            Elements children = firstE.children();

            // 获取新闻图片
            Elements imgs = children.select("img[src]");
            String imgUrl = imgs.get(0).attr("src");
            // 获取新闻标题和简介
            Element titleAndDesE = children.get(3);
            String title = titleAndDesE.select("div.c-single-text-ellipsis").first().text();
            String des = titleAndDesE.select("div.hot-desc_1m_jR").first().text();
            // 获取跳转链接
            Elements href = titleAndDesE.select("a");
            String hrefUrl = href.attr("href");

            NewsVo newsVo = new NewsVo();
            newsVo.setDes(des);
            newsVo.setHrefUrl(hrefUrl);
            newsVo.setImgUrl(imgUrl);
            newsVo.setTitle(title);
            newsList.add(newsVo);
            count ++;
        }
        return newsList;
    }

}
